package cn.zhouchao.basic.config;

import cn.zhouchao.basic.util.AjaxResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class AdviceController {
    @ResponseBody
    @ExceptionHandler
    public AjaxResult processException(Exception ex) {

        AjaxResult result;
        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
            result = AjaxResult.me().fail(exception.getBindingResult().getFieldError().getDefaultMessage());
        } else if (ex instanceof BussinessException) {
            BussinessException bex = (BussinessException) ex;
            result = AjaxResult.me().fail(bex.getMessage());
        } else {
            ex.printStackTrace();
            result = AjaxResult.me().fail();
        }
        return result;

    }

}
